package com.jiguang.Electricvehicle.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.jiguang.Electricvehicle.BytesHexStrUtils;
import com.jiguang.Electricvehicle.ChargeQrActivity;
import com.jiguang.Electricvehicle.CircleProgressBar;
import com.jiguang.Electricvehicle.MainActivity;
import com.jiguang.Electricvehicle.R;
import com.jiguang.Electricvehicle.ToastUtil;
import com.jiguang.Electricvehicle.ble.IBleCallback;
import com.jiguang.Electricvehicle.ble.InternationalBLEManager;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import me.yokeyword.fragmentation.SupportFragment;

import static com.jiguang.Electricvehicle.BytesHexStrUtils.hexToByteArray;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseSimpleFragment {
    public static final int REQUEST_ENABLE_BT = 1001;
    public static final int REQUEST_LOCATION_PERMISSION = 1002;
    private LinearLayout layoutFind;
    private LinearLayout layoutLock;
    private LinearLayout layoutUnLock;
    private LinearLayout subUnLock;
    private LinearLayout subLock;
    private LinearLayout layoutBle;
    private LinearLayout layoutStart;
    private RelativeLayout layoutError;
    private TextView textError;
    private TextView tv_total_mileage;
    private TextView text_single_mileage;
    private TextView tv_gear;
    private TextView text_energy;
    private ImageView image_start;
    private TextView text_start;
    private CircleProgressBar circleProgressBar;
    private String stubId;
    private byte[] backData;
    private int lastProgress = 90;
    private boolean isViewCreate;
    private String hex = "020e04102003000000040000000500003603";
    private SharedPreferences sharedPreferences;
    private final static String SHARED_PREFERENCES_NAME = "MySharedPreferences";

    public void setStubId(String stubId) {
        if (!TextUtils.equals(this.stubId, stubId)) {
            InternationalBLEManager.getInstance().disconnectAllDevice();
        }
        this.stubId = stubId;
        initBle();
    }

    //权限申请返回
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null) {
            return;
        }

        if (grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            initBle();
        }
    }


    public void blueOpenWithRequestLocation() {
        // 检查并请求定位权限
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
        } else {
            initBle();
        }

       /* if (AndPermission.hasPermissions(getActivity(), Permission.Group.LOCATION)) {
            initBle();
        } else {
            requestPermission();
        }*/
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        if (isViewCreate) {
            return rootView;
        }
        isViewCreate = true;
        //获取SharedPreferences对象
        sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
        stubId = sharedPreferences.getString("stubId", "");

        circleProgressBar = rootView.findViewById(R.id.circle_progress_bar1);
//        circleProgressBar.setProgress(0, 90);
        tv_total_mileage = rootView.findViewById(R.id.tv_total_mileage);
        text_single_mileage = rootView.findViewById(R.id.text_single_mileage);
        layoutBle = rootView.findViewById(R.id.layout_blue);
        tv_gear = rootView.findViewById(R.id.tv_gear);
        layoutFind = rootView.findViewById(R.id.layout_find);
        text_energy = rootView.findViewById(R.id.text_energy);
        layoutStart = rootView.findViewById(R.id.layout_start);
        image_start = rootView.findViewById(R.id.image_start);
        text_start = rootView.findViewById(R.id.text_start);
        layoutError = rootView.findViewById(R.id.layout_error);
        textError = rootView.findViewById(R.id.text_error);
        if (layoutStart.isEnabled()) {
            layoutStart.setOnClickListener(v -> {
                if (!InternationalBLEManager.getInstance().isBleConnected()) {
                    InternationalBLEManager.getInstance().cancelScan();
                    InternationalBLEManager.getInstance().disconnectAllDevice();
                    initBle();
                    return;
                }
                startSend();
            });
        }

        layoutFind.setOnClickListener(v -> {
            if (!InternationalBLEManager.getInstance().isBleConnected()) {
                InternationalBLEManager.getInstance().cancelScan();
                InternationalBLEManager.getInstance().disconnectAllDevice();
                initBle();
                return;
            }
            findSend();
        });

        layoutLock = rootView.findViewById(R.id.layout_lock);
        subLock = rootView.findViewById(R.id.sub_lock);
        if (subLock.isEnabled()) {
            layoutLock.setOnClickListener(v -> {
                if (!InternationalBLEManager.getInstance().isBleConnected()) {
                    InternationalBLEManager.getInstance().cancelScan();
                    InternationalBLEManager.getInstance().disconnectAllDevice();
                    initBle();
                    return;
                }
                lockSend();
                layoutStart.setEnabled(true);
//                layoutStart.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_start));
            });
        }

        layoutUnLock = rootView.findViewById(R.id.layout_unlock);
        subUnLock = rootView.findViewById(R.id.sub_unlock);

        if (subUnLock.isEnabled()) {
            layoutUnLock.setOnClickListener(v -> {
                if (!InternationalBLEManager.getInstance().isBleConnected()) {
                    InternationalBLEManager.getInstance().cancelScan();
                    InternationalBLEManager.getInstance().disconnectAllDevice();
                    initBle();
                    return;
                }
                unLockSend();
                layoutStart.setEnabled(false);
//                layoutStart.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_start_grey));
            });
        }

        layoutBle.setOnClickListener(v -> initBle());
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e("", "start----");
        openBle();
    }

    public void openBle() {
        if (bleEnable()) {
            if (AndPermission.hasPermissions(getActivity(), Permission.ACCESS_FINE_LOCATION) && AndPermission.hasPermissions(getActivity(), Permission.ACCESS_COARSE_LOCATION)) {
                initBle();
            } else {
                requestPermission();
            }
        }
    }

    private boolean bleEnable() {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            //表明此手机不支持蓝牙
            return false;
        }
        if (!mBluetoothAdapter.isEnabled()) {  //蓝牙未开启，则开启蓝牙
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            return false;
        } else {
            return true;
        }
    }


    @SuppressLint("WrongConstant")
    private void requestPermission() {
        AndPermission.with(getActivity())
                .runtime()
                .permission(Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION)
                .rationale((context1, data, executor) -> {
                    executor.execute();
                })
                .onGranted(permissions -> {
                    initBle();
                })
                .onDenied(permissions -> {
                    Toast.makeText(getActivity(), "请先开启定位权限", Toast.LENGTH_SHORT).show();
//                    ToastUtil.toastShortMessage("");
                })
                .start();

    }

    private byte Xor(byte[] data) {
        byte result = 0;
        for (byte b : data) {
            result ^= b;
        }
        return result;
    }

    private void initBle() {
        InternationalBLEManager.getInstance().initBle();
        if (TextUtils.isEmpty(stubId)) {
            return;
        }
        showProgress();
        connect();
    }

    private void connect() {
        InternationalBLEManager.getInstance().scanAndConnect(null, stubId, new IBleCallback() {
            @Override
            public void onStartConnect() {
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                dialog.dismiss();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                dialog.dismiss();
                Toast.makeText(getActivity(), "蓝牙已连接", Toast.LENGTH_SHORT).show();
//                ToastUtil.toastShortMessage("蓝牙已连接");
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("stubId", stubId);
                editor.apply();
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                dialog.dismiss();
                connect();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                backData = data;
                Log.d("返回数据长度---", data.length + "");
                byte lrc = Xor(data);
//                if (lrc == 1) {
                //数据校验成功
                parseData(data);
//                }
            }
        });
    }

    private String parseGear(int gear) {
        String gearStr = "--";
        switch (gear) {
            case 1:
                gearStr = "一档";
                break;
            case 2:
                gearStr = "二档";
                break;
            case 3:
                gearStr = "三档";
                break;
            case 4:
                gearStr = "四档";
                break;
        }
        return gearStr;
    }

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    protected void initEventAndData(Bundle arguments) {

    }

    ProgressDialog dialog;

    private void showProgress() {
        if (dialog == null) {
            dialog = new ProgressDialog(getContext(), R.style.ThemeProgressDialogStyle);
        }
        dialog.setMessage("蓝牙连接中...");
        dialog.setCancelable(true);
        dialog.show();
    }


    private void startSend() {
//                circleProgressBar.setProgress(99, 40);
        byte[] data = new byte[5];
        data[0] = 2;
        data[1] = 1;
        data[2] = 1;
        data[3] = Xor(data);
        data[4] = 3;
        InternationalBLEManager.getInstance().write(data);
    }

    //寻车
    private void findSend() {
        byte[] data = new byte[5];
        data[0] = 2;
        data[1] = 1;
        data[2] = 5;
        data[3] = Xor(data);
        data[4] = 3;
        InternationalBLEManager.getInstance().write(data);
    }

    //上锁
    private void lockSend() {
        byte[] data = new byte[5];
        data[0] = 2;
        data[1] = 1;
        data[2] = 7;
        data[3] = Xor(data);
        data[4] = 3;
        InternationalBLEManager.getInstance().write(data);
    }

    //解锁
    private void unLockSend() {
        byte[] data = new byte[5];
        data[0] = 2;
        data[1] = 1;
        data[2] = 6;
        data[3] = Xor(data);
        data[4] = 3;
        InternationalBLEManager.getInstance().write(data);
    }

    private void parseData(byte[] data) {
        if (data[2] == 4) {
            //行车数据
            byte[] dataByte = new byte[14];
            System.arraycopy(data, 3, dataByte, 0, 14);
            //速度
            int speed = dataByte[0];
            circleProgressBar.animateProgress(lastProgress, speed);
            lastProgress = speed;
//            circleProgressBar.setProgress(lastProgress,speed);
            //电量
            int power = dataByte[1];
            text_energy.setText("剩余电量" + power + "%");
            //档位
            int gear = dataByte[2];
            tv_gear.setText(parseGear(gear));
            //单次里程
            byte[] sm = new byte[4];
            System.arraycopy(dataByte, 3, sm, 0, 4);
            int singleMileage = BytesHexStrUtils.parseData(sm);
            text_single_mileage.setText(singleMileage + "");
            //总里程
            byte[] tm = new byte[4];
            System.arraycopy(dataByte, 7, tm, 0, 4);
            int totalMileage = BytesHexStrUtils.parseData(tm);
            tv_total_mileage.setText(totalMileage + "");
            //告警信息
            byte[] warring = new byte[2];
            Integer warringInt = null;
            try {
                System.arraycopy(dataByte, 11, warring, 0, 2);
                warringInt = BytesHexStrUtils.parseData(warring);
            } catch (Exception e) {

            }
            if (warring != null) {
                layoutError.setVisibility(View.VISIBLE);
                textError.setText("错误码 " + warringInt);
            } else {
                layoutError.setVisibility(View.GONE);
            }


//            Toast.makeText(getActivity(), "错误码" + warringInt, Toast.LENGTH_SHORT).show();
            //状态
            int state = dataByte[13];
            switch (state) {
                case 0:
                    //解锁
                    subUnLock.setEnabled(false);
                    subLock.setEnabled(true);
                    layoutStart.setEnabled(true);
                    image_start.setImageResource(R.mipmap.icon_start_grey);
                    text_start.setTextColor(Color.parseColor("#555555"));
//                    layoutStart.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_start));
                    break;
                case 1:
                    //上锁
                    subLock.setEnabled(false);
                    subUnLock.setEnabled(true);
                    layoutStart.setEnabled(true);
                    image_start.setImageResource(R.mipmap.icon_start_grey);
                    text_start.setTextColor(Color.parseColor("#555555"));
//                    layoutStart.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_start));
                    break;
                case 2:
                    //启动
                    subUnLock.setEnabled(true);
                    subLock.setEnabled(true);
                    layoutStart.setEnabled(false);
                    image_start.setImageResource(R.mipmap.icon_start);
                    text_start.setTextColor(Color.parseColor("#30EBD0"));
//                    layoutStart.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_start_grey));
                    break;

            }


//            Toast.makeText(getActivity(), "速度:" + speed + "km/h" + "电量:" + power + "档位:" + gear +
//                    "\n单次里程：" + singleMileage + "公里" + "\n总里程:" + totalMileage + "公里" + "\n状态：" + state, Toast.LENGTH_LONG).show();
        }
    }

    public void startScan() {
        ScanUtil.startScan(getActivity(), 0X01, new HmsScanAnalyzerOptions.Creator().create());
    }


}